package com.leyantech.ecp.agenx.session.manager.service;

import com.leyantech.ecp.agenx.common.redis.RedissonOperation;
import com.leyantech.ecp.agenx.common.utils.PbPrintHelper;
import com.leyantech.ecp.agenx.proto.AssistantInfo;
import com.leyantech.ecp.agenx.proto.GetOnlineAssistantsByStoreRequest;
import com.leyantech.ecp.agenx.proto.GetOnlineAssistantsByStoreResponse;
import com.leyantech.ecp.agenx.proto.SessionManagerGrpc.SessionManagerImplBase;

import com.google.inject.Singleton;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RMap;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-07.
 */
@Slf4j
@Singleton
public class SessionManageService extends SessionManagerImplBase {

  @Override
  public void getOnlineAssistantsByStore(GetOnlineAssistantsByStoreRequest request,
      StreamObserver<GetOnlineAssistantsByStoreResponse> responseObserver) {
    try {
      final String storeId = request.getStoreId();

      log.info("getOnlineAssistantsByStore storeId {}", storeId);

      final List<AssistantInfo> assistantInfoList = RedissonOperation.STORE_ASSISTANT
          .executor(storeId)
          .get(RMap::readAllValues, "readAllValues")
          .stream()
          .map(assistant ->
              AssistantInfo.newBuilder()
                  .setAssistantId(assistant.getAssistantId())
                  .setAssistantNick(StringUtils.defaultIfBlank(assistant.getAssistantName(), assistant.getAssistantId()))
                  .setClientVersion(StringUtils.defaultString(assistant.getClientVersion()))
                  .setDeviceNo(StringUtils.defaultString(assistant.getClientUuid()))
                  .setServiceMode(StringUtils.defaultString(assistant.getServiceMode()))
                  .setServerStatus(StringUtils.defaultString(assistant.getStatus(), "SERVING"))
                  .addAllServiceFuncList(assistant.getFunctions())
                  .setTimestamp(assistant.getTimestamp())
                  .setAction(StringUtils.defaultString(assistant.getAction()))
                  .setNodeId(StringUtils.defaultString(assistant.getNodeId()))
                  .build()
          )
          .collect(Collectors.toList());

      final GetOnlineAssistantsByStoreResponse response = GetOnlineAssistantsByStoreResponse
          .newBuilder()
          .addAllAssistantInfo(assistantInfoList)
          .build();

      log.info("getOnlineAssistantsByStore response {}", PbPrintHelper.lazyToJson(response));

      responseObserver.onNext(response);
    } catch (Throwable e) {
      log.error("getOnlineAssistantsByStore error", e);
      responseObserver.onError(e);
    }
    responseObserver.onCompleted();
  }

}
